package com.scau.clothes.api.sale;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.scau.clothes.core.core.entity.AjaxResult;
import com.scau.clothes.core.util.CheckObjectIsNullUtils;
import com.scau.clothes.sale.mapper.PaymentMapper;
import com.scau.clothes.sale.mapper.SaleMapper;
import com.scau.clothes.sale.model.dto.ExchangeDto;
import com.scau.clothes.sale.model.dto.ReturnDto;
import com.scau.clothes.sale.model.dto.SaleClothesDto;
import com.scau.clothes.sale.model.entity.Sale;
import com.scau.clothes.sale.model.vo.SaleClothesVo;
import com.scau.clothes.sale.service.SaleService;
import com.scau.clothes.stock.model.entity.Clothes;
import com.scau.clothes.stock.model.entity.ClothesNorm;
import com.scau.clothes.stock.service.ClothesNormService;
import com.scau.clothes.stock.service.ClothesService;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/sale")
public class SaleController {
    @Autowired
    private SaleService saleService;
    @Autowired
    private SaleMapper saleMapper;
    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private ClothesNormService clothesNormService;
    @Autowired
    private ClothesService clothesService;
    @Autowired
    private SaleService saleItemService;

    private CheckObjectIsNullUtils checkObjectIsNullUtils = new CheckObjectIsNullUtils();

    @PostMapping ("/listAllSale")
    @ApiOperation("查询订单")
    public AjaxResult listAllSale(@RequestBody Sale sale){
        List<Sale> list = saleService.listAllSale(sale);
        return !list.isEmpty() ? AjaxResult.success("查询成功",list) : AjaxResult.error("查询失败");
    }

    /**
     * 开始一次新的销售
     */
    @GetMapping("/makeNewSale")
    @ApiOperation("开始一次新的销售")
    public AjaxResult makeNewSale(){
        return AjaxResult.success(saleService.makeNewSale());
    }
    /**
     * 输入商品a
     */
    @PostMapping("/enterItem")
    @ApiOperation("输入商品")
    public AjaxResult enterItem(@RequestBody SaleClothesDto saleClothesDto){
        QueryWrapper<ClothesNorm> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clothes_number", saleClothesDto.getClothesNumber());
        queryWrapper.eq("norm_sn", saleClothesDto.getNormSn());
        SaleClothesVo clothesVo = null;
        ClothesNorm clothesNorm = clothesNormService.getOne(queryWrapper);
        if(saleClothesDto.getPrice()!=null && !clothesNorm.getPrice().equals(saleClothesDto.getPrice())){
            clothesNorm.setPrice(saleClothesDto.getPrice());
        }
        Clothes clothes = clothesService.selectClothesByClothesNumber(saleClothesDto.getClothesNumber());
        if(clothesNorm != null) {
            saleService.makeLineItem(clothesNorm, saleClothesDto.getQuantity());
            clothesVo = new SaleClothesVo(saleClothesDto.getClothesNumber(), clothes.getClothesName(),clothes.getDiscountStatus() , clothesNorm.getPrice(), saleClothesDto.getQuantity());
        }
        return AjaxResult.success(clothesVo);
    }
    /**
     * 结束销售
     */
    @GetMapping("/endSale")
    @ApiOperation("结束销售")
    public AjaxResult endSale(){
        return AjaxResult.success(saleService.endSale());
    }
    /**
     * 确认支付
     * @param cashTendered 支付金额
     */
    @PostMapping("/makePaymentByCash")
    @ApiOperation("确认支付(现金)")
    public AjaxResult makePaymentByCash(@RequestBody Sale sale, @RequestParam("cashTendered") BigDecimal cashTendered){
        return AjaxResult.success(saleService.makePaymentByCash(sale, cashTendered));
    }
    /**
     * 确认支付(支付宝)
     */
    @GetMapping("/alipay")
    @ApiOperation("确认支付(支付宝)")
    public void alipay(@RequestParam Long saleId, HttpServletResponse httpResponse) throws Exception {
        saleService.makePaymentByAlipay(saleId, httpResponse);
    }
    /**
     * 回调接口
     * 验证是否支付成功
     */
    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws Exception {
        saleService.payNotify(request);
    }
    /**
     * 退款接口
     */
    @PostMapping("/returnBack")
    public AjaxResult returnBack(@RequestBody ReturnDto returnDto) throws Exception {
        // 7天无理由退款
        String now = DateUtil.now();
        Sale sale = saleMapper.selectById(returnDto.getSaleId());
        if (sale != null) {
            // hutool工具类，判断时间间隔
            long between = DateUtil.between(paymentMapper.selectById(sale.getPaymentId()).getPayTime(),
                    DateUtil.parseDateTime(now),
                    DateUnit.DAY);
            if (between > 7) {
                return AjaxResult.error( "该订单已超过7天，不支持退款");
            }
        }
        Boolean flag = saleService.returnBack(returnDto);
        return flag ? AjaxResult.success("退款成功") : AjaxResult.error("退款失败");
    }
    @PostMapping("/exchange")
    public AjaxResult exchange(@RequestBody ExchangeDto exchangeDto){
        Boolean flag = saleService.exchange(exchangeDto);
        return flag ? AjaxResult.success("换货成功") : AjaxResult.error("换货失败");
    }
    /**
     * 取消支付
     */
    @PostMapping("/cancelSale")
    @ApiOperation("取消支付")
    public AjaxResult cancelSale(@RequestBody Sale sale){
        Sale s = saleService.cancelSale(sale);
        return !checkObjectIsNullUtils.objCheckIsNull(s) ? AjaxResult.success("取消成功",s) : AjaxResult.error("取消失败");
    }

    /**
     * 获取折扣价格
     * @param price
     * @return
     */
    @GetMapping("/getClothesNormDiscountPrice")
    public AjaxResult getClothesNormDiscountPrice(@RequestParam BigDecimal price){
        return !saleService.getClothesNormDiscountPrice(price).equals(null) ? AjaxResult.success("获取成功", saleService.getClothesNormDiscountPrice(price))
                : AjaxResult.error("获取失败");
    }

    @GetMapping("/page")
    @ApiOperation("分页操作")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, Sale sale){
        List<Sale> list = saleService.listAllSale(sale);
        Collections.reverse(list); // 反转saleList
        Page page = new Page(pageNum, pageSize);
        int total = list.size();
        page.setTotal(total);
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize,total);
        page.addAll(list.subList(startIndex,endIndex));
        PageInfo pageInfo = new PageInfo<>(page);
        return AjaxResult.success(pageInfo);
    }

}